package com.stephenone.customviewdemo

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

private val IMAGE_WIDTH = 150f.dp
private val IMAGE_PADDING = 20f.dp
private val XFERMODE = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)


/**
 *
 * 两个图像重叠 要包括透明部分才起作用
 *
 * */
class XfermodeView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val circleBitmap = Bitmap.createBitmap(150f.dp.toInt(),150f.dp.toInt(),Bitmap.Config.ARGB_8888)
    private val squareBitmap = Bitmap.createBitmap(150f.dp.toInt(),150f.dp.toInt(),Bitmap.Config.ARGB_8888)
    
    init{
        val canvas = Canvas(circleBitmap)
        paint.color = Color.CYAN
        canvas.drawOval(50f.dp,0f.dp,150f.dp,100f.dp,paint)
        paint.color = Color.MAGENTA
        canvas.setBitmap(squareBitmap)
        canvas.drawRect(0f.dp,50f.dp,100f.dp,150f.dp,paint)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //离屏缓冲
        val count = canvas.saveLayer(
            IMAGE_PADDING,
            IMAGE_PADDING,
            IMAGE_PADDING + IMAGE_WIDTH,
            IMAGE_PADDING + IMAGE_WIDTH,
            paint
        )
        canvas.drawBitmap(circleBitmap,IMAGE_PADDING,IMAGE_PADDING,paint)
        paint.xfermode = XFERMODE
        canvas.drawBitmap(squareBitmap,IMAGE_PADDING,IMAGE_PADDING,paint)
        paint.xfermode = null
        canvas.restoreToCount(count)
    }

}